<?php 
namespace Emos\Field;

use Emos\Common;
use Emos\Db;

class File extends AbstractControl {
    protected $prefix;
    protected $docRoot;
    protected $urlRoot;
    
    protected $legalExtensions = array();
    protected $forbiddenExtensions = array('php', 'phtml', 'php3', 'php4', 'php5', 'php6', 'htaccess');
        
    public function __construct($prefix='/var/') {
        $this->nullable = true;
        
        $this->prefix = $prefix;
        $this->docRoot = $_SERVER['DOCUMENT_ROOT'];
        $this->urlRoot = $prefix;        
    }    

    public function setValidExtensions(array $extensions) {
        $this->validExtensions = $extensions;
    }    
    
    public function validate() {
        $originalName = @$_FILES[$this->htmlName]['name'];
        $ext = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
        
        if($this->forbiddenExtensions && in_array($ext, $this->forbiddenExtensions)) {
            $this->error = Common::t('not legal file extension', array('extensions'=>strtoupper(implode(', ', $this->forbiddenExtensions))));
            return false;            
        }        

        if($this->legalExtensions && !in_array($ext, $this->legalExtensions)) {
            $this->error = Common::t('forbidden file extension', array('extensions'=>strtoupper(implode(', ', $this->legalExtensions))));
            return false;            
        }        
        
        return true;
    }

    public function html() {        
        $html = '';

        $html .= "<input type='file' name='{$this->htmlName}' value='' />";
        
        if($this->value) {            
            $size = ceil(@filesize("{$this->docRoot}{$this->prefix}{$this->value}") / 1024);
              
            $ext = '?';
            if(preg_match('/  \. ([a-z0-9]{1,7})  $  /xi', $this->value, $m)) {
                $ext = strtoupper($m[1]);            
            }            
            
            $html .= "<div><a href='{$this->prefix}".Common::plain($this->value)."' target='_blank'>{$ext}, {$size} KB</a></div>";
        }        
        
        return $html;
   }
   
    public function getDdlFields() {
        return array(
            $this->dbName => "VARCHAR(40)"
        );
    }  
    
    public function update() {
        $originalName = @$_FILES[$this->htmlName]['name'];
        $tempName     = @$_FILES[$this->htmlName]['tmp_name'];        
            
        if(@$_POST["{$this->htmlName}_isNull"] == 'null') {
            $this->deleteFiles();
            return array($this->dbName => new Db\SqlExpression("NULL"));        
        }
        else if(is_uploaded_file($tempName)) {
            $this->deleteFiles();
            $storedFileName = $this->storeFile($tempName, $originalName);            

            return array($this->dbName => $storedFileName);        
        }            
            
        return null;      
    }
            
    function delete() {                    
        $this->deleteFiles();                    
    }    
    
    function storeFile($tempName, $originalName) {
        if(preg_match('/  \. ([a-z0-9]{1,7})  $  /xi', $originalName, $m)) {
            $ext = '.'.strtolower($m[1]);            
        }
        else {
            $ext = '.dat';
        }                        
        $storeName = md5(mt_rand()).$ext;

        copy($tempName, "{$this->docRoot}{$this->prefix}{$storeName}");                
        return $storeName;
    }    
    
    protected function deleteFiles() {         
        if($this->value != null) {
            @unlink("{$this->docRoot}{$this->prefix}{$this->value}");
        }
    }              
}

